package custom.base.http.listener;


import android.app.Dialog;
import android.content.Context;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import custom.base.entity.base.BaseResponse;
import custom.base.http.data.NetCode;
import custom.base.log.MLog;
import custom.base.widgets.LoadLayout;

import java.io.UnsupportedEncodingException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by luozi on 2015/12/29.
 * 响应监听，泛型
 */
public abstract class ResponseListener<T> implements Callback<BaseResponse<T>>, NetCode {
    protected AliveCallback liveNetCallback;
    protected Context context;

    public ResponseListener(AliveCallback liveNetCallback) {
        this.liveNetCallback = liveNetCallback;
        this.context = liveNetCallback.currentContext();
    }

    public ResponseListener(final Context context) {
        this.context = context;
        this.liveNetCallback = new AliveCallback() {
            @Override
            public boolean isAlive() {
                return true;
            }

            @Override
            public Context currentContext() {
                return context;
            }
        };
    }

    /**
     * 处理空对象数据异常，默认关闭,当页面为空时自动改变页面状态
     */
    protected boolean dealNullResponseData() {
        return false;
    }

    /**
     * 弹框等待绑定
     */
    protected Dialog getDialog() {
        return null;
    }

    /**
     * 布局加载提示绑定
     */
    protected LoadLayout getLoadLayout() {
        return null;
    }

    /**
     * 布局加载提示绑定
     */
    protected SwipeRefreshLayout getRefreshLayout() {
        return null;
    }


    @Override
    public final void onResponse(Call call, Response response) {
        if (!liveNetCallback.isAlive()) {//当环境为空的时候拒绝回调，为了避免界面被回收控件为空的问题
            call.cancel();
            return;
        }
        if (getDialog() != null) {//自动绑定dialog展示状态
            getDialog().cancel();
            getDialog().dismiss();
        }
        if (getRefreshLayout() != null)
            getRefreshLayout().setRefreshing(false);

        BaseResponse<T> baseResponse = (BaseResponse<T>) response.body();
        MLog.d("requestReponse", baseResponse);
        if (baseResponse == null) {
            if (getDialog() != null) {//自动绑定dialog展示状态
                getDialog().cancel();
                getDialog().dismiss();
            }
            if (getRefreshLayout() != null)
                getRefreshLayout().setRefreshing(false);
            if (getLoadLayout() != null) {//自动绑定展示状态
                getLoadLayout().setStatus(LoadLayout.TYPE_ERROR);
            }
            onResponseError(call, new Throwable("网络错误->baseResponse为空"));
            return;
        }
        switch (baseResponse.getCode()) {
            case RESPONSE_SUCCESS:
                if (dealNullResponseData() && baseResponse.getData() == null) {
                    if (getLoadLayout() != null) {//自动绑定展示状态
                        getLoadLayout().setStatus(LoadLayout.TYPE_SUCCESS_EMPTY);
                    }
                    onResponseCodeError(call, new BaseResponse().setMsg("返回data对象为空"));
                } else {
                    if (getLoadLayout() != null) {//自动绑定展示状态
                        getLoadLayout().setStatus(LoadLayout.TYPE_SUCCESS);
                    }

                    try {
                        onResponseSuccess(call, baseResponse);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                break;
            default:
                if (getLoadLayout() != null) {//自动绑定展示状态
                    getLoadLayout().setStatus(LoadLayout.TYPE_ERROR);
                }
                onResponseCodeError(call, baseResponse);
                break;
        }

    }

    @Override
    public final void onFailure(Call call, Throwable t) {
        if (!liveNetCallback.isAlive())//当环境为空的时候拒绝回调，为了避免界面被回收控件为空的问题
            return;
        if (getDialog() != null) {//自动绑定dialog展示状态
            getDialog().cancel();
            getDialog().dismiss();
        }
        if (getRefreshLayout() != null)
            getRefreshLayout().setRefreshing(false);
        if (getLoadLayout() != null) {//自动绑定展示状态
            getLoadLayout().setStatus(LoadLayout.TYPE_ERROR);
        }
        MLog.e(t.getMessage());
        if (call.isCanceled()) {
            onResponseCancel(call, t);
        } else {
            onResponseError(call, t);
        }
    }

    /**
     * 响应成功
     */
    public abstract void onResponseSuccess(Call call, BaseResponse<T> response) throws UnsupportedEncodingException;

    /**
     * 请求错误
     */
    public void onResponseError(Call call, Throwable t) {

    }

    /**
     * 请求错误
     */
    public void onResponseCodeError(Call call, BaseResponse<T> response) {
    }


    /**
     * 取消请求
     * 根据框架而定，暂时弃用
     */
    public void onResponseCancel(Call call, Throwable t) {
    }

}
